package com.lancoo.answer.view.fragment.composition.answer;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.lancoo.answer.R;
import com.lancoo.answer.helper.ConfirmDialogHelper;
import com.lancoo.answer.helper.LoadDialogHelper;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ExamViewBean;
import com.lancoo.answer.model.bean.ImgAnswerCallBackBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.ImgRecognitionCollectionBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.ImageCallBackEventBean;
import com.lancoo.answer.model.eventBean.ImageEventBean;
import com.lancoo.answer.widget.combinationView.PictureAnswerView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2021/12/8 14:15
 * Description:
 */
public class CompositionPictureAnswerFragment extends Fragment{

    private static final String TAG = "CompositionPictureAnswe";
    private Item item;
    private int typeIndex =-1;
    private int quesIndex =-1;
    private int childIndex =-1;
    private int itemIndex =-1;
    private AlertDialog loadDialog;
    private PictureAnswerView pictureAnswerView;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_composition_answer_type_picture, container, false);
    }

    public void setItem(Item item) {
        this.item = item;
    }


    public static Fragment loadFragment(int typeIndex, int queseIndex, int childIndex,int itemIndex){
        Log.e(TAG,"pic loadFragment itemIndex:"+itemIndex);
        CompositionPictureAnswerFragment fragment=new CompositionPictureAnswerFragment();
        Bundle mBundle=new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX,typeIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX,queseIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX,childIndex);
        mBundle.putInt(AnswerConstant.KEY_ITEMINDEX,itemIndex);
        fragment.setArguments(mBundle);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void initView(View view){
        Log.e("aaaa","图片作答初始化view");
        EventBus.getDefault().register(this);
        if(getArguments()==null){
            return;
        }
        typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        childIndex = getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        itemIndex = getArguments().getInt(AnswerConstant.KEY_ITEMINDEX);
        Log.e(TAG,"pic  initView:"+itemIndex);
        final TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        if(constantExamBean==null){
            return;
        }
        if(taskControlBean==null){
            return;
        }
        List<Type> typeList = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if(typeList==null){
            return;
        }
        Type type = typeList.get(typeIndex);
        if(type==null){
            return;
        }
        List<Ques> quesList = type.getQuesList();
        if(quesList==null){
            return;
        }
        Ques ques = quesList.get(quesIndex);
        if(ques ==null){
            return;
        }
        List<Child> childList = ques.getChildList();
        if(childList==null){
            return;
        }
        Child child = childList.get(childIndex);
        if(child==null||child.getItemList()==null){
            return;
        }
        item = child.getItemList().get(itemIndex);
        pictureAnswerView = view.findViewById(R.id.pav);
        pictureAnswerView.setIndex(typeIndex,quesIndex,childIndex,itemIndex);
        pictureAnswerView.initData(item, ques.getTypeNo());
        pictureAnswerView.setCallBack(new PictureAnswerView.PictureAnswerCallBack() {

            @Override
            public void onDeletCallBack(int position) {

                ImageEventBean imageEventBean=new ImageEventBean();
                imageEventBean.setTypeIndex(typeIndex);
                imageEventBean.setQueseIndex(quesIndex);
                imageEventBean.setChildIndex(childIndex);
                imageEventBean.setItemIndex(itemIndex);
                imageEventBean.setOperateType(1);
                imageEventBean.setPosition(position);
                Log.e("imgO","外部开始图片上传"+new Gson().toJson(imageEventBean));
                EventBus.getDefault().post(imageEventBean);
            }

            @Override
            public void onImgListUpLoad(List<String> imgs) {
                upLoadImgFiles(imgs);
            }

            @Override
            public void onImgTxtUpdate(String content) {

            }
        });
    }



    private List<String> tempImgList;
    private void upLoadImgFiles(List<String> imgList){
        tempImgList=imgList;
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        int mediaAnswerSaveType = taskControlBean.getMediaAnswerSaveType();
        ImageEventBean imageEventBean=new ImageEventBean();
        imageEventBean.setTypeIndex(typeIndex);
        imageEventBean.setQueseIndex(quesIndex);
        imageEventBean.setChildIndex(childIndex);
        imageEventBean.setChildIndex(itemIndex);
        if(item.getImagePathList()==null){
            imageEventBean.setPosition(0);
        }else{
            imageEventBean.setPosition(item.getImagePathList().size());
        }
        imageEventBean.setImgList(imgList);
        EventBus.getDefault().post(imageEventBean);
        if(mediaAnswerSaveType==0){
            ImageCallBackEventBean bean=new ImageCallBackEventBean();
            bean.setSuccess(true);
            bean.setTypeIndex(typeIndex);
            bean.setChildIndex(childIndex);
            bean.setQueseIndex(quesIndex);
            bean.setItemIndex(itemIndex);
            bean.setImgList(imgList);
            onImageEventCallBack(bean);
            return;
        }
        loadDialog = LoadDialogHelper.showLoadDialog(getContext(), R.string.ev_uploading,false);
        for (String path:imgList){
            Log.e("aaa","收到图片："+ path);
        }
    }


    /**
     * 图片上传
     */
    //
    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImageEventCallBack(final ImageCallBackEventBean callBackEventBean) {
        Log.e(TAG,"图片上传执行结果回调");
        if(callBackEventBean.getTypeIndex()== typeIndex &&
                callBackEventBean.getQueseIndex()== quesIndex &&
                callBackEventBean.getChildIndex()== childIndex&&
                callBackEventBean.getItemIndex()==itemIndex){
            List<String> imgList = callBackEventBean.getImgList();
            if(loadDialog!=null&&loadDialog.isShowing()){
                loadDialog.dismiss();
            }
            Log.e(TAG,"1 item 图片大小"+item.getImagePathList().size());
            if(imgList!=null&&imgList.size()>0){
                Log.e("aaa","回调："+imgList.get(0));
                List<String> imagePathList = item.getImagePathList();
                if(imagePathList==null){
                    imagePathList=new ArrayList<>();
                }
                imagePathList.addAll(imgList);
                item.setImagePathList(imagePathList);
                Log.e(TAG,"2 item 图片大小"+item.getImagePathList().size());
                List<ImgRecognitionCollectionBean> list=new ArrayList<>();
                if(item.getImagePathList()==null){
                    item.setImagePathList(new ArrayList<>());
                }
                Log.e(TAG,"3 item 图片大小"+item.getImagePathList().size());
                if(tempImgList.size()==item.getImagePathList().size()){
                    for (String s:tempImgList){
                        ImgRecognitionCollectionBean bean=new ImgRecognitionCollectionBean();
                        bean.setLocalPath(s);
                        list.add(bean);
                    }
                }else{
                    for (int i = 0; i < item.getImagePathList().size()-tempImgList.size(); i++) {
                        ImgRecognitionCollectionBean bean=new ImgRecognitionCollectionBean();
                        bean.setLocalPath(item.getImagePathList().get(i));
                        list.add(bean);
                    }
                    for (String s:tempImgList){
                        ImgRecognitionCollectionBean bean=new ImgRecognitionCollectionBean();
                        bean.setLocalPath(s);
                        list.add(bean);
                    }
                }
                Log.e(TAG,"4 item 图片大小"+item.getImagePathList().size());
                item.setImgRecognitionDataList(list);
                if(pictureAnswerView!=null){
                    pictureAnswerView.updateImgAdapterData();
                }
            }else{
                showImgUploadFailureDialog();
            }
        }
    }

    /**
     * 重新上传图片作答
     */
    private void showImgUploadFailureDialog(){
        ConfirmDialogHelper.showConfirmDialog(getContext(), 2,
                getString(R.string.ev_picture_upload_failure), getString(R.string.ev_upload_retry),
                getString(R.string.ev_cancel), new ConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        if(tempImgList==null||tempImgList.size()==0){
                            return;
                        }
                        upLoadImgFiles(tempImgList);

                    }
                });
    }


    public void updateKeyboardShowState(boolean isShow){
        if(pictureAnswerView==null){
            return;
        }
//        pictureAnswerView.updateRecognitionStyle(isShow);
    }


    public void adjustFontSize(){
        if(pictureAnswerView==null){
            return;
        }
        pictureAnswerView.adjustFontSize();
    }

    public void updateImgAnswerCallBack(ImgAnswerCallBackBean bean){
        if(pictureAnswerView==null){
            return;
        }
        String imgUrl = bean.getImgUrl();
        List<String> list=new ArrayList<>();
        list.add(imgUrl);
        pictureAnswerView.updateImgAnswerCallBack(list);
    }

}
